package com.nanxhs.jmh;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * 测试字符串拼接的性能
 *
 * @author: haibin.tang
 * @date: 2021/1/27
 */
@Threads(8)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode({Mode.AverageTime})
@Warmup(iterations = 2, time = 1)
@Measurement(iterations = 2, time = 1)
public class StringJoinBenchmark {

    @Benchmark
    public void stringBuilder() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int index = 0; index < 100000; ++index) {
            stringBuilder.append(index);
        }
    }

    @Benchmark
    public void stringBuffer() {
        StringBuffer stringBuffer = new StringBuffer();
        for (int index = 0; index < 100000; ++index) {
            stringBuffer.append(index);
        }
    }

    @Benchmark
    public void string() {
        String str = "";
        for (int index = 0; index < 100000; ++index) {
            str += index;
        }
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(StringJoinBenchmark.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}
